package com.example.petstore.web.controller;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.example.petstore.web.model.AdminModel;
import com.example.petstore.web.model.ErrorModel;

@Controller
@SessionAttributes("adminUser")
@RequestMapping("/admin")
public class AdminController {

	@RequestMapping(value="/toLogin")
	public String toLogin(@ModelAttribute("adminModel") AdminModel adminModel) {
		return "authority/login";
	}
	
	@RequestMapping(value="/login", method = {RequestMethod.GET, RequestMethod.POST})
	public String login(Model model, @ModelAttribute("adminModel") AdminModel adminModel, @RequestParam(value="backUrl", defaultValue="") String backUrl) throws IOException {
		
		boolean valid = true;
		String message = null;
		if(adminModel == null) {
			message = "非法操作";
			valid = false;
		} else if (!"admin".equals(adminModel.getUsername())) {
			message = "用户名不存在";
			valid = false;
		} else if (!"123456".equals(adminModel.getPassword())) {
			message = "密码不正确";
			valid = false;
		}
		
		if(!valid) {
			ErrorModel errorModel = new ErrorModel();
			errorModel.setMessage(message);
			errorModel.setPage("返回上一页", "javascript:history.back();");
			model.addAttribute("errorModel", errorModel);
			return "comm/error";
		} else {
			model.addAttribute("adminUser", adminModel.getUsername());
			if(StringUtils.isBlank(backUrl)) {
				return "redirect:/product/list";
			} else {
				return "redirect:" + backUrl;
			}
		}
	}
	
	@RequestMapping(value="/logout")
	public String logout(ModelMap modelMap, SessionStatus sessionStatus, @ModelAttribute("adminModel") AdminModel adminModel) throws IOException {
		sessionStatus.setComplete();
		return "authority/login";
	}
}
